package com.sj.parksdk.fragment.pay;

import android.content.Context;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.ruffian.library.widget.RTextView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.adapter.base.delegate.SimpleDelegateAdapter;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.net.http.MyNetApi;
import com.sj.parksdk.net.http.callback.TipRequestCallBack;
import com.sj.parksdk.net.request.MGetRequest;
import com.sj.parksdk.net.result.databean.Data_NearbyPark;
import com.sj.parksdk.setting.Constans;
import com.sj.parksdk.setting.Dictionary;
import com.sj.parksdk.setting.Extras;
import com.sj.parksdk.utils.RefreshState;
import com.sj.parksdk.utils.Utils;
import com.sj.parksdk.utils.bdlocation.LocationService;
import com.sj.parksdk.widget.ClearEditText;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.core.PageOption;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.imageview.ImageLoader;
import com.xuexiang.xui.widget.imageview.strategy.DiskCacheStrategyEnum;
import com.xuexiang.xui.widget.statelayout.StatefulLayout;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;

import butterknife.BindView;
import butterknife.OnClick;

@Page(name = "套餐购买")
public class FragmentPurchasePlan extends BaseFragment {

    @BindView(R2.id.et_search)
    ClearEditText etSearch;
    @BindView(R2.id.recycler_park)
    RecyclerView recyclerPark;
    @BindView(R2.id.ll_state)
    StatefulLayout llState;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.tv_notice)
    TextView tvNotice;
    @BindView(R2.id.bt_next)
    SuperButton btNext;

    private SimpleDelegateAdapter<Data_NearbyPark> nearParkAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_fragment_purchase_plan;
    }

    @Override
    protected void initViews() {
        initAdapter();
    }

    private void initAdapter() {
        nearParkAdapter = new SimpleDelegateAdapter<Data_NearbyPark>(R.layout.parksdk_adapter_nearby_park, new LinearLayoutHelper()) {
            @Override
            protected void bindData(@NonNull RecyclerViewHolder holder, int position, Data_NearbyPark model) {
                if (model == null) return;
                holder.text(R.id.tv_name, model.getName());
                holder.text(R.id.tv_address, model.getAddress());
                holder.text(R.id.tv_describe, model.getChargeStandard());
                holder.text(R.id.tv_distance, model.getDistanceStr());
                holder.image(R.id.iv_select,ResUtils.getDrawable(position == mSelectPosition?R.drawable.park_ic_selected_common :R.drawable.park_ic_unselected_common));
                RTextView tvStatus = holder.findViewById(R.id.tv_status);
                int stateColor = 0;
                if (Dictionary.Park.Park_Colose == model.getStatus()) {
                    tvStatus.setText(ResUtils.getString(R.string.park_closed));
                    stateColor = ResUtils.getColor(R.color.color_9);
                } else if(Dictionary.Park.Park_Green == model.getStatus()){
                    stateColor = ResUtils.getColor(R.color.color_green_remain);
                    tvStatus.setText("剩余"+model.getRemainSpace());
                }else if(Dictionary.Park.Park_Red == model.getStatus()){
                    stateColor = ResUtils.getColor(R.color.color_red_remain);
                    tvStatus.setText("剩余"+model.getRemainSpace());
                }else{
                    stateColor = ResUtils.getColor(R.color.color_tip_orange);
                }
                tvStatus.getHelper().setTextColorNormal(stateColor);
                tvStatus.getHelper().setBorderColorNormal(stateColor);
                ImageView ivThu = (ImageView) holder.findViewById(R.id.iv_image);
                ImageLoader.get().loadImage(ivThu, model.getThumbImage(), ResUtils.getDrawable(R.drawable.xui_ic_default_img), DiskCacheStrategyEnum.NONE);
                holder.click(R.id.ll_item, v -> setSelectPosition(position));
            }
        };
        WidgetUtils.initRecyclerView(recyclerPark, DensityUtils.dp2px(1),ResUtils.getColor(R.color.color_cut_line));
        recyclerPark.setAdapter(nearParkAdapter);
    }

    @Override
    protected void initListeners() {
        initRefreshListener();
        initNoticeClickListener();
    }


    private void initNoticeClickListener() {
        tvNotice.setText(getPrivacyContent(getContext()));
        tvNotice.setMovementMethod(LinkMovementMethod.getInstance());
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索的时候隐藏软键盘
                    Utils.hideKeyboard(etSearch);
//                    searchNearByPark(RefreshState.refresh);
                    refresh.autoRefresh();
                    return true;
                }
                return false;
            }
        });
    }

    /**
     * @return 购买须知
     */
    private static SpannableStringBuilder getPrivacyContent(Context context) {
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder()
                .append("*请认真阅读并同意").append(getUserPrivacyLink(context, ResUtils.getString(R.string.pay_buy_notice), Constans.API_AGREEMENT))
                .append("后再确认支付");
        return stringBuilder;
    }

    /**
     * @return
     */
    private static SpannableString getUserPrivacyLink(Context context, String privacyName, String privacyUrl) {
        SpannableString spannableString = new SpannableString(privacyName);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                Utils.goWeb(context, privacyUrl);
            }

//            @Override
//            public void updateDrawState(@NonNull TextPaint ds) {
//                super.updateDrawState(ds);
//                ds.setUnderlineText(false);
//            }
        }, 0, privacyName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    private void initRefreshListener() {
        //下拉刷新
        refresh.setOnRefreshListener(refreshLayout -> {
            pageIndex = 1;
            searchNearByPark(RefreshState.refresh);
        });
        //上拉加载
        refresh.setOnLoadMoreListener(refreshLayout -> {
            pageIndex ++;
            searchNearByPark(RefreshState.more);
        });
        refresh.autoRefresh();
    }

    @OnClick({R2.id.tv_buy_record, R2.id.bt_next})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.tv_buy_record) {
            if (checkLogin()) openPage(FragmentPackageRecord.class);
        } else if (id == R.id.bt_next) {
            nextStep();
        }
    }

    private void nextStep() {
        Bundle params = new Bundle();
        params.putString(Extras.PARK_NAME, nearParkAdapter.getSelectItem().getName());
        params.putLong(Extras.PARK_ID, nearParkAdapter.getSelectItem().getId());
        params.putString(Extras.PARK_ADDRESS, nearParkAdapter.getSelectItem().getAddress());
        PageOption option = new PageOption(FragmentPurchasePlanConfirm.class).setAddToBackStack(true).setBundle(params);
        openPage(option);
    }

    private int pageIndex = 1;

    private void searchNearByPark(int flag) {
        new MGetRequest(MyNetApi.PARK_LOTS_NEARBY)
                .visit()
                .params(MyNetApi.PakLotsNearby.longitude, LocationService.get().getLocatedInfo().getmLongitude())
                .params(MyNetApi.PakLotsNearby.latitude, LocationService.get().getLocatedInfo().getmLatitude())
                .params(MyNetApi.PakLotsNearby.range, 5.0)
                .params(MyNetApi.PakLotsNearby.pageIndex, pageIndex)
                .params(MyNetApi.PakLotsNearby.pageSize, 20)
                .params(MyNetApi.PakLotsNearby.coordinateType, Constans.LOCATION_TYPE)
                .params(MyNetApi.PakLotsNearby.keyword, etSearch.getText().toString())
                .execute(new TipRequestCallBack<Data_NearbyPark>() {
                    @Override
                    public void onSuccess(Data_NearbyPark data) throws Throwable {
                        if (data == null || data.getItems() == null) {
                            llState.showCustom(emptyStatus(R.drawable.park_ic_empty_park));
                            return;
                        }
                        switch (flag) {
                            case RefreshState.refresh:
                                if(data.getItems().size() == 0) llState.showCustom(emptyStatus(R.drawable.park_ic_empty_park));
                                nearParkAdapter.refresh(data.getItems());
                                refresh.finishRefresh();
                                if (data.getTotal() == data.getItems().size()) {
                                    refresh.setNoMoreData(true);
                                }
                                break;
                            case RefreshState.more:
                                nearParkAdapter.loadMore(data.getItems());
                                if (data.getTotal() == nearParkAdapter.getData().size()) {
                                    refresh.finishLoadMoreWithNoMoreData();
                                    break;
                                }
                                refresh.finishLoadMore();
                                break;
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        llState.showError(null);
                        switch (flag) {
                            case RefreshState.refresh:
                                refresh.finishRefresh();
                                break;
                            case RefreshState.more:
                                refresh.finishLoadMore(false);
                                break;
                        }
                    }
                });
    }
}
